<template>
  <el-dialog :title="fileBaseTitle" :fullscreen="dialogFullscree" :visible.sync="dialogVisible"
    :close-on-click-modal="false" width="80%" class="showDialogClass" :before-close="handleClose">
    <el-container style="height: auto; border: 1px solid #eee; padding-right: 20px">
      <el-drawer title="请点击选择上传目录" :visible.sync="drawer" :direction="direction" ref="tclb" width="20%"
        :append-to-body="appendToBody" :before-close="handleCloseDrawer">
        <div class="tree mt10">
          <el-tree :data="treedata" :props="props" :load="loadNode" lazy v-model="checkedNodes"
            @node-click="handleNodeClick" />
        </div>
        <div class="demo-drawer__footer">
          <el-button @click="drawer = false">取 消</el-button>
          <el-button type="primary" @click="drawer = false">确定</el-button>
        </div>
      </el-drawer>

      <el-container width="400px">
        <el-form ref="form" :model="form" label-width="130px">
          <el-form-item label="选择要发布的文件">
            <el-upload class="upload-demo" :action="uploadUrl" :on-preview="handlePreview" :on-remove="handleRemove"
              :on-success="uploadSuccess" :on-error="uploadError" :on-exceed="handleExceed" :before-upload="beforeUpload"
              :before-remove="beforeRemove" :multiple="fileMultiple" :limit="1" :file-list="fileList">
              <el-button size="small" type="primary" :disabled="readOnly">
                点击上传
              </el-button>
              <div slot="tip" class="el-upload__tip">
                允许上传pdf格式,且不超过100MB
              </div>
            </el-upload>
          </el-form-item>
          <el-row>
            <el-col v-if="!readOnly" :span="24" style="max-width: 90%" />
            <el-row>
              <el-col :span="24" style="max-width: 80%">
                <el-form-item label="文件名称">
                  <el-input :disabled="true" v-model="form.docName" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24" style="max-width: 80%">
                <el-form-item label="文档标题">
                  <el-input :disabled="readOnly" v-model="form.docTitle" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24" style="max-width: 80%">
                <el-form-item label="文件副标题">
                  <el-input :disabled="readOnly" v-model="form.fileSubTitle" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12" style="max-width: 40%">
                <el-form-item label="文号">
                  <el-input :disabled="readOnly" v-model="form.fileNumber" />
                </el-form-item>
              </el-col>
              <el-col :span="12" style="max-width: 40%">
                <el-form-item label="文件发布目录">
                  <el-input :disabled="true" placeholder="单击此处选择发布目录" style="max-width: 70%"
                    v-model="form.treeIndexDesc" />
                  <el-button v-if="!readOnly" @click="openDrawer" type="primary" style="margin-left: 5px">
                    选择目录
                  </el-button>
                  <el-input v-show="false" v-model="form.treeIndex" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12" style="max-width: 40%">
                <el-form-item label="发文单位">
                  <el-input :disabled="readOnly" v-model="form.releaseUnit" placeholder="请输入" style="max-width: 70%" />
                </el-form-item>
              </el-col>
              <el-col :span="12" style="max-width: 40%">
                <el-form-item label="发文日期">
                  <el-date-picker :disabled="readOnly" type="date" placeholder="选择日期" format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd" style="max-width: 70%" v-model="form.fileReleaseUnitDate" />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 标签 -->
            <el-col :span="24" style="max-width: 80%">
              <el-form-item label="标签">
                <el-tag :disabled="readOnly" v-model="form.fileLabel" style="cursor:pointer"
                  v-for="(item, index) in items" size="small" @click="changeColor(index)" :key="index"
                  :effect="item.tagEffect">
                  {{ item.label }}
                </el-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="max-width: 80%">
              <el-form-item label="保密级别:">
                <el-radio-group v-model="form.secrecyLevel">
                  <el-radio label="公开">
                    公开
                  </el-radio>
                  <el-radio label="内部">
                    内部
                  </el-radio>
                  <el-radio label="秘密">
                    秘密
                  </el-radio>
                  <el-radio label="机密">
                    机密
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="max-width: 80%">
              <el-form-item label="是否发布:">
                <el-radio-group v-model="form.fileIsPublic">
                  <el-radio :label="1">
                    发布
                  </el-radio>
                  <el-radio :label="0">
                    暂不发布
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="max-width: 80%">
              <el-form-item label="是否置顶:">
                <el-radio-group v-model="form.fileIsTop">
                  <el-radio :label="1">
                    置顶
                  </el-radio>
                  <el-radio :label="0">
                    不置顶
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" style="max-width: 80%">
              <el-form-item label="是否热点:">
                <el-radio-group v-model="form.fileIsHot">
                  <el-radio :label="1">
                    热点
                  </el-radio>
                  <el-radio :label="0">
                    非热点
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24" style="max-width: 80%">
              <el-form-item label="描述">
                <el-input :disabled="readOnly" type="textarea" v-model="form.describe" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-container>
    </el-container>
    <span slot="footer" class="dialog-footer" v-if="!readOnly">
      <el-button type="primary" @click="onSubmit">
        {{ buttonText }}
      </el-button>
      <el-button @click="handleClose"> 取消 </el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  fileBaseDetail,
  fileBaseSave,
} from "@/api/knowledge/fileBase";
import { getTreeDataList } from "@/api/knowledge/diretory";
import { getList } from "@/api/knowledge/label";
import webapp from "@/config/webapp";
import store from "@/store";


class Photo {
  constructor(name, url) {
    this.name = name;
    this.url = url;
  }
}

export default {
  name: `addFile`,
  components: {},
  mounted() { },
  computed: {
    scrollerHeight: function () {
      return `${window.innerHeight - 150}px`;
    },
  },
  data() {
    return {
      readOnly: false,
      fileBaseTitle: ``,
      items: [],
      buttonText: ``,
      fileList: [],
      drawer: false,
      direction: `ltr`,
      treedata: [], //tree数据
      props: {
        label: `name`,
        children: `children`, // 显示子节点的字段名
        isLeaf: (node) => !node.isParent && !node.children,
      },
      checkable: true, // 是否显示复选框
      checkedNodes: [],
      form: {
        id: null,
        fileNumber: ``, //文号
        docType: ``,
        docTitle: ``,
        docNum: ``,
        fileReleaseUnitDate: ``,
        releaseUnit: ``,
        docPath: ``,
        treeIndex: ``,
        treeIndexDesc: ``,
        fileIsPublic: 1, //是否发布
        secrecyLevel: `内部`,
        fileDiretoryName: ``, //名称
        describe: ``,
        fileSubTitle: ``, //文件副标题
        fileIsTop: 0, //是否置顶
        fileIsHot: 0, //是否热点
        fileLabel: ``, //标签
      },
      uploadUrl: webapp.uploadUrl,
      heightY: `${window.innerHeight - 260}px`,
      appendToBody: true,
      dialogFullscree: false,
      dialogVisible: false,
      fileMultiple: false,
      radio: `0`,
      // 分页参数
      pageParams: {
        total: 0,
        currentPage: 1,
        pageSize: 30,
        pageSizes: [30, 50, 100],
      },
      tableDetail: {},
      searchkeys: [],
      fileBussinessTypeCode: "111",
      fileBusinessTypeId: "111"
    };
  },
  filters: {
    dealValue(value) {
      if (value) {
        value = value.replace(`&nbsp;`, ``);
        return value;
      }
      return value;
    },
  },
  methods: {
    initdata() {
      this.items.map(item => {
        item.tagEffect = `plain`;
        return item;
      })
      this.form = JSON.parse(JSON.stringify({
        id: null,
        fileNumber: ``, //文号
        docType: ``,
        docTitle: ``,
        docNum: ``,
        fileReleaseUnitDate: ``,
        releaseUnit: ``,
        docPath: ``,
        treeIndex: ``,
        treeIndexDesc: ``,
        fileIsPublic: 1, //是否发布
        secrecyLevel: "内部",
        fileDiretoryName: ``, //名称
        describe: ``,
        fileSubTitle: ``, //文件副标题
        fileIsTop: 0, //是否置顶
        fileIsHot: 0, //是否热点
        fileLabel: ``, //标签
      }));
      this.searchkeys = JSON.parse(JSON.stringify([]));
    },
    init(id, flag) {
      this.readOnly = flag == `look`;
      this.radio = `0`;
      this.getTreeData();
      this.getTagDataList()
      if (id != null) {
        this.fileBaseDetail(id);
        this.buttonText = `保存修改`;
        this.fileBaseTitle = `编辑文件`;
      }
      else {
        this.buttonText = `立即创建`;
        this.fileBaseTitle = `发布文件`;
        this.dialogVisible = true;
      }
    },
    // 获取编辑的回显
    async fileBaseDetail(id) {
      this.initdata();
      await this.getTagDataList();
      const params = {
        userId: store.getters.user_id.toString(),
        token: store.getters.token.toString(),
        userName: store.getters.userName.toString(),
        data: { fileId: id },
      };
      fileBaseDetail(params).then((data) => {
        if (data.result) {
          this.tableDetail = data.resultdata.data;
          this.form.id = data.resultdata.data.fileId;
          this.form.docName = data.resultdata.data.fileTitle; //文件名称
          this.form.docTitle = data.resultdata.data.fileTitle; //文档标题
          this.form.fileSubTitle = data.resultdata.data.fileSubTitle
            ? data.resultdata.data.fileSubTitle
            : ``; //文件副标题
          this.form.fileNumber = data.resultdata.data.fileNumber
            ? data.resultdata.data.fileNumber
            : ``; //文号
          this.form.fileIsPublic = data.resultdata.data.fileIsPublic; //是否发布
          this.form.fileIsTop = data.resultdata.data.fileIsTop; //是否置顶
          this.form.fileIsHot = data.resultdata.data.fileIsHot; //是否热点
          this.form.secrecyLevel = data.resultdata.data.fileSecrecyLevel;//保密级别
          this.form.fileReleaseUnitDate = data.resultdata.data.fileReleaseUnitDate; //发文时间
          this.form.releaseUnit = data.resultdata.data.fileReleaseUnitName; //发文单位
          this.searchkeys = data.resultdata.data.fileLabel; //标签
          this.form.treeIndexDesc = data.resultdata.data.fileDiretoryName;
          this.form.treeIndex = data.resultdata.data.fileDiretoryId;
          this.form.docPath = data.resultdata.data.fileUrl;
          this.form.describe = data.resultdata.data.description;
          const photoList = [];
          photoList.push(new Photo(this.form.docName, this.form.docPath));
          this.fileList = photoList;

          const fileLabel = data.resultdata.data.fileLabel;
          if(fileLabel) {
            // 不爲空的的時候
            let labelList = fileLabel.split(',')
            this.searchkeys = labelList;
            this.items.forEach(e => {
              if(labelList.includes(e.label)) {
                this.$set(e, 'tagEffect', 'dark')
              }
            })
          }
          this.dialogVisible = true;
          this.$forceUpdate();
        }
      });
    },
    getTagDataList() {
      return new Promise((resolve, reject) => {
        const params = {
          data: { fileBusinessTypeId: this.fileBusinessTypeId },
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
          userName: store.getters.userName.toString(),
        };
        getList(params).then((data) => {
          if (data.result) {
            const items = [];
            data.resultdata.data.forEach(function (obj, index) {
              items.push({
                label: obj.labelName,
                index: index,
                tagEffect: `plain`,
              });
            });

            this.items = items;
          }
          resolve()
        }).catch(() => {
          reject
        });
      })
    },

    onSubmit() {
      const params = {
        data: {
          fileTitle: this.form.docTitle,
          fileSubTitle: this.form.fileSubTitle,
          fileNumber: this.form.fileNumber,
          fileIsPublic: this.form.fileIsPublic,
          fileIsTop: this.form.fileIsTop,
          fileIsHot: this.form.fileIsHot,
          fileSecrecyLevel: this.form.secrecyLevel,
          fileReleaseUnitDate: this.form.fileReleaseUnitDate,
          fileReleaseUnitName: this.form.releaseUnit,
          fileUrl: this.form.docPath,
          fileDiretoryId: this.form.treeIndex,
          description: this.form.describe,
          fileLabel: this.searchkeys.toString(),
        },
        userId: store.getters.user_id.toString(),
        token: store.getters.token.toString(),
        userName: store.getters.userName.toString(),
      };
      if (this.fileBaseTitle === `发布文件`) {
        fileBaseSave(params).then((data) => {
          if (data.result === true) {
            this.$message({
              type: `success`,
              message: `操作成功`,
            });
            this.cancel();
            this.$emit(`refresh`);
          }
          else {
            this.$message({
              type: `warning`,
              message: data.message,
            });
          }
        });
      }
      else if (this.fileBaseTitle === `编辑文件`) {
        const param = {
          data: {
            fileId: this.tableDetail.fileId,
            fileTitle: this.form.docTitle,
            fileSubTitle: this.form.fileSubTitle,
            fileNumber: this.form.fileNumber,
            fileIsPublic: this.form.fileIsPublic,
            fileIsTop: this.form.fileIsTop,
            fileIsHot: this.form.fileIsHot,
            fileSecrecyLevel: this.form.secrecyLevel,
            fileReleaseUnitDate: this.form.fileReleaseUnitDate,
            fileReleaseUnitName: this.form.releaseUnit,
            fileUrl: this.form.docPath,
            fileDiretoryId: this.form.treeIndex,
            description: this.form.describe,
            fileLabel: this.searchkeys.toString(),

          },
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
          userName: store.getters.userName.toString(),
        };
        fileBaseSave(param).then((data) => {
          if (data.result === true) {
            this.$message({
              type: `success`,
              message: `操作成功`,
            });
            this.cancel();
            this.$emit(`refresh`);
          }
          else {
            this.$message({
              type: `warning`,
              message: data.message,
            });
          }
        });
      }
    },
    // 抽屉里的tree树渲染
    getTreeData() {
      const params = {
        userId: store.getters.user_id.toString(),
        token: store.getters.token.toString(),
        userName: store.getters.userName.toString(),
        data: {
          fileBussinessTypeCode: this.fileBussinessTypeCode,
          fileDiretoryId: null,
        },
      };
      getTreeDataList(params).then((data) => {
        if (data.result === true) {
          this.treedata = data.resultdata.data;
        }
        else {
          this.$message({
            type: `warning`,
            message: `获取信息出错`,
          });
        }
      });
    },
    // tree的懒加载数据
    loadNode(node, resolve) {
      if (node.level === 0) {
        return resolve(this.treedata);
      }
      if (node.level > 9999) return resolve([]);
      // 请求子节点数据
      setTimeout(() => {
        const params = {
          userId: store.getters.user_id.toString(),
          token: store.getters.token.toString(),
          userName: store.getters.userName.toString(),
          data: {
            fileBussinessTypeCode: this.fileBussinessTypeCode,
            fileDiretoryId: node.data.id,
          },
        };
        getTreeDataList(params).then((data) => {
          if (data.result === true) {
            node.childNodes = [...node.childNodes, ...data.resultdata.data];
            const updatedChildren = node.childNodes.map((child) => {
              child.checked =
                this.checkable &&
                this.checkedNodes.some((node) => node.id === child.id);
              return child;
            });
            resolve(updatedChildren);
          }
          else {
            this.$message({
              type: `warning`,
              message: `获取信息出错`,
            });
          }
        });
      }, 500);
    },
    //点击tree树进行选择
    handleNodeClick(data, b, c) {
      this.form.treeIndex = data.id;
      this.form.treeIndexDesc = data.name;
      this.$refs.tclb.closeDrawer();
    },
    handleCloseDrawer(done) {
      done();
    },
    changeColor(id) {
      // 点击改变主题
      const baginState = this.items[id].tagEffect == `plain`;
      this.items[id].tagEffect =
        this.items[id].tagEffect == `plain` ? `dark` : `plain`;
      this.searchkeys = [];
      for (let i = 0; i < this.items.length; i++) {
        if (this.items[i].tagEffect == `dark`) {
          this.searchkeys.push(this.items[i].label);
        }
      }
    },
    openDrawer() {
      this.drawer = true;
    },
    handlePreview(file) {
      console.log(`点击了文件列表中的${file}`);
    },
    beforeUpload(file) {
      const fileType = file.name.substring(file.name.lastIndexOf(`.`) + 1);
      let isPassType = false;
      if (fileType == `pdf` || fileType == `PDF`) {
        isPassType = true;
      }
      const isLt100M = file.size / 1024 / 1024 < 100;
      if (!isPassType) {
        this.$message.error(`文件类型只能是 pdf 格式!`);
      }
      if (!isLt100M) {
        this.$message.error(`上传文件大小不能超过 100MB!`);
      }
      return isPassType && isLt100M;
    },
    uploadSuccess(response, file, fileList) {
      this.form.docName = file.name.substring(0, file.name.lastIndexOf(`.`));
      this.form.docTitle = file.name.substring(0, file.name.lastIndexOf(`.`));
      this.form.docType = `.${file.name.substring(file.name.lastIndexOf(`.`) + 1)}`;
      if (response.success) {
        this.form.docPath = response.url;
      }
    },
    uploadError(err, file, fileList) {
      // console.log("上传失败了",err, file, fileList)
    },
    handleRemove(file, fileList) {
      console.log(`删掉`, file, fileList);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
        } 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    cancel() {
      this.dialogVisible = false;
      this.fileList = [];
      this.searchKeys = [];
      this.form = {
        docName: ``,
        docType: ``,
        docTitle: ``,
        docNum: ``,
        fileReleaseUnitDate: ``,
        releaseUnit: ``,
        docPath: ``,
        treeIndex: ``,
        treeIndexDesc: ``,
        isRelease: `0`,
        fileIsPublic: 1,
        fileIsTop: 0,
        fileIsHot: 0,
        secrecyLevel: "内部",
        describe: ``,
      };
    },
    handleClose() {
      this.cancel();
    },
  },
};
</script>

<style scoped>
.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.el-upload-list__item:first-child {
  margin-top: 30px !important;
}

.el-row {
  margin-bottom: 20px;

  & :last-child {
    margin-bottom: 0;
  }
}

.el-col {
  border-radius: 4px;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

>>>.el-drawer {
  width: 30% !important;
}

>>>.el-tree {
  margin-left: 20px;
}

>>>.el-dialog {
  width: 70% !important;
}

.el-tree {
  min-width: 100%;
  height: calc(100% - 150px);
  display: inline-block;
}

.tree {
  overflow: auto;
  height: 680px;
  min-width: 100%;
}

.demo-drawer__footer .el-button {
  width: 270px;
  height: 35px;
  margin-left: 5px;
  margin-bottom: 10px;
}

>>>.el-upload-list {
  width: 500px;
}

>>>.el-upload-list__item-name {
  width: 300px;
}
</style>
